<template>
  <div class="checkout-step3">
    <div class="payment-header">
      <h2>Pay order</h2>
      <div class="amount">{{ useCurrency.currentCurrency.unit }}{{ finalAmountDisplay > 0 ? proxy.$ConvertPrice(finalAmountDisplay) : proxy.$ConvertPrice(totalAmount) }}</div>
    </div>

    <div class="payment-details">
      <div class="payment-detail-item">
        <span>Total product amount：</span>
        <span>{{ useCurrency.currentCurrency.unit }}{{ proxy.$ConvertPrice(totalAmount) }}</span>
      </div>
      <div class="payment-detail-item" v-if="props.shippingFee && props.shippingFee.fee > 0">
        <span>Freight：</span>
        <span>{{ useCurrency.currentCurrency.unit }}{{ proxy.$ConvertPrice(props.shippingFee.fee) }}</span>
      </div>
      <div class="payment-detail-item" v-if="props.shippingFee && props.shippingFee.insuranceFee > 0">
        <span>Shipping Insurance：</span>
        <span>{{ useCurrency.currentCurrency.unit }}{{ proxy.$ConvertPrice(props.shippingFee.insuranceFee) }}</span>
      </div>
      <div class="payment-detail-item" v-if="props.shippingFee && props.shippingFee.dutyInsuranceFee > 0">
        <span>Duty Insurance：</span>
        <span>{{ useCurrency.currentCurrency.unit }}{{ proxy.$ConvertPrice(props.shippingFee.dutyInsuranceFee) }}</span>
      </div>
      <div class="payment-detail-item discount" v-if="props.discount > 0">
        <span>Save：</span>
        <span>-{{ useCurrency.currentCurrency.unit }}{{ proxy.$ConvertPrice(props.discount) }}</span>
      </div>
    </div>

    <div v-if="loading" class="loading-state">
      <a-spin />
      <p>Loading payment status...</p>
    </div>
    <div class="payment-method" v-if="goodsTotal && orderId ">
      <StripePayment
          :amount="goodsTotal"
          :orderId="orderId"
          :addressDetail="addressDetail"
          @payment-success="checkPayment"
          @prev-step="prevStep"
      />
    </div>
  </div>
</template>

<script setup>
import {computed, getCurrentInstance, onMounted, ref} from 'vue';
import { message } from 'ant-design-vue';
import StripePayment from "@/components/srPay/SrCheckoutForm.vue";
import {useCurrencyStore} from '@/store/currency.ts'
import { getDetailAddress } from "@/api/user";

const { proxy } = getCurrentInstance();
const useCurrency = useCurrencyStore();
const props = defineProps({
  selectedItems: {
    type: Array,
    default: () => []
  },
  currentStep: {
    type: Number,
    default: 0
  },
  paymentMethod: {
    type: String,
    default: 'stripe - card'
  },
  addressId: {
    type: [Number, String],
    default: 0
  },
  shippingFee: {
    type: Object,
    default: () => ({
      fee: 0,
      insuranceFee: 0,
      dutyInsuranceFee: 0
    })
  },
  discount: {
    type: Number,
    default: 0
  },
  finalAmount: {
    type: Number,
    default: 0
  },
  goodsAmount: {
    type: Number,
    default: 0
  },
  orderId: {
    type: [Number, String],
    default: 0
  }
});
const loading = ref(true);
const addressDetail = ref(null);
const emit = defineEmits(['update:step']);
const totalAmount = computed(() => {
  // const total = props.selectedItems.reduce((total, item) => {
  //   return total + (item.price * item.quantity);
  // }, 0);
  return Math.floor(props.goodsAmount * 100) / 100;
});
const finalAmountDisplay = computed(() => {
  const final = props.finalAmount;
  return Math.floor(final * 100) / 100;
});

const totalShippingFee = computed(() => {
  if (typeof props.shippingFee === 'number') {
    return props.shippingFee;
  }

  if (!props.shippingFee) {
    return 0;
  }

  const fee = props.shippingFee.fee || 0;
  const insuranceFee = props.shippingFee.insuranceFee || 0;
  const dutyInsuranceFee = props.shippingFee.dutyInsuranceFee || 0;

  return fee + insuranceFee + dutyInsuranceFee;
});

const goodsTotal = computed(() => {
  if (props.goodsAmount > 0) {
    return props.goodsAmount;
  }

  const baseAmount = props.goodsAmount > 0 ? props.goodsAmount : totalAmount.value;
  return baseAmount + totalShippingFee.value - Number(props.discount);
});
const prevStep = () => {
  emit('update:step', 1);
};

const checkPayment = () => {
  // 模拟支付检查
  // message.success('Payment successfully！');
  emit('update:step', 3);
};

// 查询地址详情
const getAddressDetail = async () => {
  if (!props.addressId) return;

  try {
    const res = await getDetailAddress(props.addressId);
    if (res.code === 200) {
      addressDetail.value = res.result;
    } else {
      console.error('Failed to get address details:');
    }
  } catch (error) {
    console.error('Failed to get address details:', error);
  }
}

onMounted(()=>{
  getAddressDetail();
  setTimeout(() => {
    loading.value = false;
  }, 1500);
})

</script>

<style scoped>
.checkout-step3 {
  max-width: 600px;
  margin: 0 auto;
  padding: 24px;
}

.payment-header {
  text-align: center;
  margin-bottom: 32px;
}

.payment-header h2 {
  font-size: 24px;
  margin-bottom: 16px;
}

.amount {
  font-size: 36px;
  color: #f5222d;
  font-weight: bold;
}

.payment-details {
  margin-bottom: 32px;
}

.payment-detail-item {
  margin-bottom: 8px;
}

.payment-detail-item span:first-child {
  font-weight: bold;
}

.payment-detail-item.discount {
  color: #52c41a;
}

.payment-method {
  display: flex;
  align-items: center;
  margin-bottom: 32px;
  padding: 16px;
  background: #f5f5f5;
  border-radius: 8px;
}

.method-icon {
  margin-right: 16px;
}

.payment-icon {
  font-size: 32px;
  color: #1890ff;
}

.method-info h3 {
  margin: 0 0 8px 0;
  font-size: 18px;
}

.method-info p {
  margin: 0;
  color: #666;
}

.qr-code {
  text-align: center;
  margin-bottom: 32px;
}

.code-placeholder {
  display: inline-block;
  padding: 32px;
  background: #f5f5f5;
  border-radius: 8px;
}

.qr-icon {
  font-size: 64px;
  color: #1890ff;
  margin-bottom: 16px;
}

.payment-actions {
  display: flex;
  justify-content: center;
  gap: 16px;
}

.loading-state {
  text-align: center;
  margin: 40px 0;
}

@media (max-width: 768px) {
  .checkout-step3 {
    padding: 16px;
  }

  .payment-header h2 {
    font-size: 20px;
  }

  .amount {
    font-size: 28px;
  }

  .payment-icon {
    font-size: 24px;
  }

  .method-info h3 {
    font-size: 16px;
  }

  .qr-icon {
    font-size: 48px;
  }
}
</style>
